using UnityEngine;
using System.Collections;

public class slingshot : MonoBehaviour {
	
	public GameObject pum;
	//public GameObject showscore;
	public bool ball_grabbed;
	public bool ball_flying;
	public Vector3 startpos;
	public GameObject newball;
	public float respawntime = 0f;
	public bool respawned = false;

	void Start () {
		startpos=transform.position;
		rigidbody2D.gravityScale=0f;
		ball_grabbed = false;
		ball_flying=false;
		respawntime = 0f;
		respawned = false;
	}

	void Shockwave()
	{
		object[] allObjects = FindObjectsOfTypeAll(typeof(GameObject)) ;
		foreach(object o in allObjects)
		{
			GameObject obj = (GameObject)o;
			if (obj.activeInHierarchy && obj.rigidbody2D!=null)
			{
				float dist = Vector3.Distance(transform.position, obj.transform.position);
				float max_dist=10f;
				if(dist<=max_dist)
				{
					Vector3 dir = Vector3.Normalize(transform.position-obj.transform.position);
					obj.rigidbody2D.WakeUp();
					obj.rigidbody2D.velocity -= (new Vector2(dir.x,dir.y)*(max_dist-dist))*1f;
				}
			}
		}
	}

	void Respawn()
	{
		GameObject clone2=Instantiate(newball,startpos,transform.rotation) as GameObject;
		respawned=true;

		GameObject clone;
		clone=Instantiate(pum,transform.position,transform.rotation) as GameObject;
		Destroy(clone,3f);
	}
	
	void Update () {
		
		if(ball_flying==false && ball_grabbed==false)
			transform.position=startpos;

		// ritsan venytys
		if(ball_grabbed)
		{
			rigidbody2D.velocity = new Vector3(0f,0f,0f);
			transform.position = Camera.main.ScreenPointToRay (Input.mousePosition).GetPoint(Vector3.Distance(transform.position,Camera.main.transform.position)-0.5f);
			transform.position = new Vector3(transform.position.x,transform.position.y,0.0f);

			// maksimivenytys
			float max_dist = 2.0f;
			if(Vector3.Distance(transform.position,startpos)>max_dist)
			{
				Vector3 dir=transform.position-startpos;
				transform.position=startpos+dir.normalized*max_dist;
			}

			// irti päästäminen
			if(!Input.GetKey(KeyCode.Mouse0))
			{
				rigidbody2D.velocity = (startpos-transform.position)*15f;
				rigidbody2D.gravityScale=1f;
				ball_grabbed = false;
				ball_flying = true;
			}
			collider2D.enabled=false;
		}
		else
			collider2D.enabled=true;
		
		if(ball_flying)
		{
			respawntime += Time.deltaTime;
			if(respawntime > 3f)
			{
				Respawn();
				Destroy(gameObject);
				Shockwave();
			}

		}
	}
	
	void OnMouseDown()
	{
		if(ball_flying==false)
			ball_grabbed=true;
	}
	void OnCollisionEnter2D(Collision2D c)
	{
		if(ball_flying || c.gameObject.tag=="frog")
		{
			Respawn();
			Destroy(gameObject);
			Shockwave();
		}
	}
}

